﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Dimok.Web.UI.JS.JQuery.VSDoc.js" assembly="Dimok.Web.UI" />
/// <reference name="Dimok.Web.UI.JS.MSAjaxExtentions.js" assembly="Dimok.Web.UI"/>
Type.registerNamespace("Dimok");
Dimok.CarPriceModes = function() {
  if (arguments.length !== 0) throw Error.parameterCount();
  throw Error.notImplemented();
}
Dimok.CarPriceModes.prototype = { None:"", Upload:"GetUploadCarPrice", FirstTime: "", Current: "GetCarPrice_Current" }
Dimok.CarPriceModes.registerClass("Dimok.CarPriceModes");

Dimok.Table = function(element) {
  Dimok.Table.initializeBase(this, [element]);
  this._RGE = null;
  Dimok.Accessorize(this);
}
Dimok.Table.prototype = {
  _txtAttachName: "",
  _attachButton: null,
  _fileAttach: null,
  _attachment: { docID: 0, fileName: "" },
  _$attachmentsPanel: null,

  _carPriceMode: Dimok.CarPriceModes.None,
  _callCarPriceWebMethod: Function.emptyFunction(),
  _getGUID: function(key) {
    return Dimok.Ajax({ methodName: "GetList_GuidDocs", wsObject: WSA }, [this.get_wsEntityType(), key]);
  },
  _getImagePages: function(loanID) {
    return Dimok.Ajax({ methodName: "GetImagePages", wsObject: WSA }, [loanID]);
  },
  _getDecisionPrograms: function(bankID) {
    return Dimok.Ajax({ methodName: "GetDecisionPrograms", wsObject: WSA }, [bankID || 0]);
  },
  _getAttachmentsHtml: function(key) {
    return Dimok.Ajax({ methodName: "GetDocumentsTable", wsObject: WSA }, [this.get_wsEntityType(), key]);
  },
  showDoc: function(docID, fileName, doSave) {
    this._attachment = { docID: docID, fileName: fileName };
    setTimeout("$find('" + this.get_element().id + "')._showDoc();", 5000);
  },
  _showDoc: function(e, context) {
    var $tr = $J(this).parents("tr:first");
    var docID = $tr.attr("ID");
    var fileName = $tr.children().eq(context._$attachmentsPanel.data("tableLegend")["Name"]).text();
    var doSave = true;
    //var docID = this._attachment.docID, fileName = this._attachment.fileName, 
    var url = "/Manager/webservices/common.asmx/ShowDocument?ID=" + docID + "&DoSave=" + (!!doSave) + "&" + fileName;
    if (!doSave)
      Dimok.FindMainMenu().openWindow(url, "ATTACHMENT" + docID);
    else location.href = url;
  },
  deleteDoc: function(e, context) {
    if (!confirm("Sure?")) return;
    var $tr = $J(this).parents("tr:first");
    var docID = $tr.attr("ID");
    return Dimok.Ajax({ methodName: "Document_Delete", wsObject: WSA }, { ID: docID });
  },
  _runTest: function() {
    /* Starter
    _testKey: {}, _testCount: 0, _$testDiv: null,
    this._testKey = key;
    this._testCount = 1000;
    this._runTest();*/
    if (this._testCount-- <= 0) return;
    if (!this._$testDiv) this._$testDiv = $J("#DIVInTheDocument");
    if (this._$attachmentsPanel) this._$attachmentsPanel.each(function() { this.innerHTML = ""; this.outerHTML = "" }).empty();
    this._$testDiv.append(this._$attachmentsPanel).empty();
    this._$attachmentsPanel = null;
    setTimeout(Function.createDelegate(this, this._showAttachments), 100);
  },
  _hideAttachments: function() {
    if (!this._$testDiv) this._$testDiv = $J("#DIVInTheDocument");
    if (this._$attachmentsPanel) this._$attachmentsPanel.empty().each(function() { this.innerHTML = ""; this.outerHTML = "" }).empty();
    this._$testDiv.append(this._$attachmentsPanel).empty();
    this._$attachmentsPanel = null;
  },
  _showAttachments: function(key) {
    var attachments = this._getAttachmentsHtml(key || this.get_testKey());
    var attachmentsHtml = attachments.html;
    DIVInTheDocument.insertAdjacentHTML("beforeEnd", attachmentsHtml);
    var left = Math.max(10, ((event || {}).clientX || 0) - 10);
    var top = Math.max(30, ((event || {}).clientY || 0) - 10);
    this._$attachmentsPanel = $J(DIVInTheDocument.firstChild).appendTo(document.body)
      .draggable()
      .keypress(Function.createCallback(function(e, context) { if (event.keyCode == 27) context._hideAttachments(); }, this))
      .css({ position: "absolute", left: left, top: top, backgroundColor: "white" })
      .focus();
    this._$attachmentsPanel.data("tableLegend", attachments.legend);
    var $table = this._$attachmentsPanel.find("table:first");
    $table.addClass("floater");
    $table.append("<caption align='right'><B>X</B></caption>").find("B")
    .click(Function.createDelegate(this, this._hideAttachments));
    this._$attachmentsPanel.find("[action='show']").click(Function.createCallback(this._showDoc, this));
    this._$attachmentsPanel.find("img[action='delete']").click(Function.createCallback(this.deleteDoc, this));
    //    .dialog({
    //      height: this._$attachmentsPanel.height(), width: this._$attachmentsPanel.width(),
    //      position: [(event || {}).y || 0, (event || {}).y || 0],
    //      resize: function() {
    //        $J(this).children("div").height($J(this).parent()[0].style.pixelHeight - $J(this).parent().children()[0].offsetHeight * 2);
    //        $J(this).children("div").width($J(this).parent()[0].style.pixelWidth - 30);
    //      }
    //    });
    //      .css({ position: "absolute", left: (event || {}).y || 0, top: (event || {}).x || this._testCount })
    //      .focus().blur(function() { debugger; });
    //setTimeout(Function.createDelegate(this, this._runTest), 100);
  },
  initialize: function() {
    Dimok.Table.callBaseMethod(this, 'initialize');
    this.get_RGE().add_rowDataBound(Function.createDelegate(this, function(sender, eventArgs) {
      var item = eventArgs.get_item();
      var loanPages = item.get_cell("LoanPages");
      if (loanPages) {
        loanPages = $J("IMG", loanPages)[0];
        $clearHandlers(loanPages);
        loanPages.keys = this.get_RGE().getGridDataItemKeys(item);
        this.addHandlers(loanPages, { 'mouseover': Dimok.FindMainMenu().showLoanPagesMenu }, this);
      }
    }));
    this.get_RGE().add_rowContextMenuItemClicked(Function.createDelegate(this, function(sender, eventArgs) {
      var key = this.get_RGE().getGridDataItemKeys(this.get_RGE().get_contextMenuGridDataItem());
      var loanID = eventArgs.get_GridDataItem().get_dataItem().LoanID;
      switch (eventArgs._item.get_value()) {
        case "GetCarPrice":
          if (!this.set_batchKeys(true).length || !confirm("Get price for " + _loans(this.get_batchKeys()) + "?")) return this.set_batchKeys();
          eventArgs.set_cancel(true);
          return this._getCarPrice(parseInt(eventArgs.get_item().get_attributes().getAttribute("TypeID")));
        case "GetCarHistory":
          var url = "/manager/menu/menufloat.htm?";
          var servicePath = "servicePath=" + escape("/Manager/webservices/common.asmx");
          var serviceFunc = "&serviceFunc=" + escape("BookValueHistory()");
          var VIN = eventArgs._GridDataItem.get_dataItem().VIN;
          var title = "&title=" + VIN;
          return showModelessDialog(url + servicePath + serviceFunc + title,
            { opener: top, funcParams: { VIN: VIN} }, Dimok.DialogParams(100, 50).join(";"));
        case "ShowImage":
          var folderID = parseInt(eventArgs.get_item().get_attributes().getAttribute("FolderID"));
          var url = "/Manager/Common/ShowApplImageFolder.aspx?pdf=pdf.pdf&ApplID=" + loanID + "&folderID=" + folderID + "&Time=1233927682610";
          return Dimok.FindMainMenu().openWindow(url, "IMAGES_" + loanID + "_" + folderID);
        case "ShowImages":
          return Dimok.FindMainMenu().openWindow("/Manager/Imaging/Imaging.aspx?ApplID=" + loanID + "&", "IMAGES_" + loanID);
        case "ShowDocs":
          return this._showAttachments(key);
          //          var title = "&title=" + Sys.Serialization.JavaScriptSerializer.serialize(key);
          //          return location.href = "/Manager/webservices/common.asmx/GetList_Document?ID=" + 1 + "&DoSave=" + true;
          //          return showModelessDialog(url + servicePath + serviceFunc + title,
          //            { opener: top, funcParams: { GUID: guid },
          //              showDoc: Function.createDelegate(this, this.showDoc),
          //              deleteDoc: Function.createDelegate(this, this.deleteDoc)
          //            }, Dimok.DialogParams(100, 50).join(";"));
        case "LoanInfo":
          var loanID = eventArgs.get_GridDataItem().get_dataItem().LoanID;
          eventArgs.set_cancel(true);
          return Dimok.FindMainMenu().openWindow("/Manager/Underwriting/FQuest/Decision.aspx?ApplID=" + loanID + "&NoLock=1", "CREDIT_" + loanID);
        case "ShowCredit":
          var loanID = eventArgs.get_GridDataItem().get_dataItem().LoanID;
          eventArgs.set_cancel(true);
          return Dimok.FindMainMenu().openWindow("/Manager/Common/Credit.aspx?ApplID=" + loanID, "CREDIT_" + loanID);
      }
      function _loans(batchKeys) {
        return batchKeys.length == 1 ? Sys.Serialization.JavaScriptSerializer.serialize(batchKeys[0]) + " loan" : batchKeys.length + " loans";
      }
    }));
    if (this.get_attachButton()) this.addHandlers(this.get_attachButton(), { 'click': this._onFileAttach }, this);
    this.get_RGE().add_rowContextMenuShowing(Function.createDelegate(this, this._onRowContextMenuShowing_Dimok$Table));
  },
  dispose: function() {
    if (this.get_$attachmentsPanel()) this.get_$attachmentsPanel().remove();
    Dimok.Table.callBaseMethod(this, 'dispose');
  },
  _onRowContextMenuShowing_Dimok$Table: function(sender, eventArgs) {
    var mi = eventArgs.get_contextMenu()._findItemByText("Images");
    if (mi) {
      var imagePages = this._getImagePages(eventArgs.get_keys().get_LoanID());
      eventArgs.get_contextMenu().trackChanges();
      mi.get_items().clear();
      Array.forEach(imagePages, function(ip) {
        var childItem = new Telerik.Web.UI.RadMenuItem();
        childItem.set_text(ip.ImageType);
        childItem.set_value("ShowImage");
        childItem.get_attributes().setAttribute("FolderID", ip.ID);
        mi.get_items().add(childItem);
      });
      eventArgs.get_contextMenu().commitChanges();
    }
    var mi = eventArgs.get_contextMenu()._findItemByText("Decision");
    if (mi) {
      var programs = this._getDecisionPrograms(22);
      eventArgs.get_contextMenu().trackChanges();
      mi.get_items().clear();
      Array.forEach(programs, function(ip) {
        var childItem = new Telerik.Web.UI.RadMenuItem();
        childItem.set_text(ip.Program);
        childItem.set_value("Decision");
        childItem.get_attributes().setAttribute("ProgramID", ip.ID);
        mi.get_items().add(childItem);
      });
      eventArgs.get_contextMenu().commitChanges();
    }
  },
  // Path-through
  _showLoadPanel: function() { return this.get_RGE()._showLoadPanel(); },
  _hideLoadPanel: function() { return this.get_RGE()._hideLoadPanel(); },
  get_grid: function() { return this.get_RGE().get_grid(); },
  get_MTV: function() { return this.get_RGE().get_MTV(); },
  get_batchKeys: function() { return this.get_RGE().get_batchKeys(); },
  set_batchKeys: function() { return this.get_RGE().set_batchKeys.apply(this.get_RGE(), arguments); },
  findGridDataItem: function(keys) { return this.get_RGE().findGridDataItem(keys); },
  bindRow: function(result, gridDataItem) { return this.get_RGE().bindRow(result, gridDataItem); },
  rebind: function(clearSelected) { return this.get_RGE().rebind(clearSelected); },
  clearSelected: function() { return this.get_RGE().clearSelected(); },
  get_wsEntityType: function() { return this.get_RGE().get_wsEntityType(); },
  // *** Menu Handlers
  _onFileAttach: function(eventArgs) {
    var fileUploadRegEx = this.get_fileAttach().value.match(/([^\\]+)([.][^.]+)$/) || [];
    var fileName = this.get_txtAttachName().value || fileUploadRegEx[1];
    if (!fileName) return alert("Need a file name first.");
    var key = this.get_RGE().getGridDataItemKeys(this.get_RGE().get_contextMenuGridDataItem());
    var guid = this._getGUID(key);
    $J.ajaxFileUpload({
      fileElementId: this.get_fileAttach().id,
      hiddens: { hdnFileName: fileName + fileUploadRegEx[2], hdnGuidDocs: guid },
      dataType: "html",
      success: Function.createDelegate(this, function(data) {
        var result = Sys.Serialization.JavaScriptSerializer.deserialize(data);
        if ((result || {}).message) $J.popup.show("File Upload Error", unescape(result.message));
        else alert("Done!");
      }),
      url: "/Manager/Common/AttachDocument.aspx"
    });
    if (!this.get_fileAttach($J(eventArgs.target).parent().find("input:file")[0]))
      alert("File Upload element is not found.\nYou won't be able to upload more file.");
  },
  _getCarPrice: function(bookValueTypeID, isBatch) {
    if (isBatch === undefined) { this._showLoadPanel(); isBatch = this.get_batchKeys().length > 1; }
    var keys = Dimok.$A(this.get_batchKeys().shift());
    var gridDataItem = this.findGridDataItem(keys) || undefined;
    if (!keys) return this._hideLoadPanel();
    var selfDelegate = Function.createDelegate(this, function() { this._getCarPrice(bookValueTypeID, isBatch); });
    var batchTitle = isBatch ? "Car Price " : "";
    var onCompleteDelegate = Function.createDelegate(this, function(result) {
      this._onComplete(result, keys, batchTitle, gridDataItem, selfDelegate);
    });
    //Dimok.Ajax({ async: true, methodName: this.get_carPriceMode(), wsObject: WSA }, [Object.firstValue(keys), bookValueTypeID], onCompleteDelegate, onCompleteDelegate, this);
    //this._getCarPriceMethod(Object.firstValue(keys), bookValueTypeID, onCompleteDelegate, onCompleteDelegate);
    this._callCarPriceWebMethod(keys, bookValueTypeID, onCompleteDelegate, onCompleteDelegate);
  },
  // *** Batch Handlers
  _onComplete: function(result, keys, batchTitle, gridDataItem, batchDelegate) {
    var keysString = Sys.Serialization.JavaScriptSerializer.serialize(keys);
    if (result && result.get_message)
      var bubbleError = { element: gridDataItem, error: keysString + '\n' + result.get_message() };
    var bubbleComplete = { element: gridDataItem, html: keysString + "." + this.get_batchKeys().length + " left.", topFly: 0 }
    if (gridDataItem) {
      if (batchTitle) gridDataItem.set_selected(false);
      if (!bubbleError && result) this.bindRow(result, gridDataItem);
      bubbleComplete.element = gridDataItem.get_element();
      if (bubbleError) bubbleError.element = gridDataItem.get_element();
    }
    if (bubbleError) $J.bubbleTip($J.extend({ element: this.get_grid().get_element() }, bubbleError));
    $J.bubbleTip($J.extend({ element: this.get_grid().get_element() }, bubbleComplete));
    if (this.get_batchKeys().length) return setTimeout(batchDelegate, 10);
    this._hideLoadPanel();
    if (batchTitle) {
      this.clearSelected();
      $J.bubbleTip({ element: this.get_grid().get_element(), html: batchTitle + "Batch completed.", flash: true, callback: Function.createDelegate(this, this.rebind) });
      return true;
    }
  }
}
Dimok.Table.registerClass('Dimok.Table', motobankcorp.UI.Behavior);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
